import random
import time
from django.shortcuts import render, redirect
from django.contrib.auth import login, logout
from django.core.cache import cache
from django.http import JsonResponse
from django.conf import settings
from .forms import PhoneNumberForm, VerificationCodeForm
from .models import User
import requests
from urllib.parse import urlencode
import uuid
import hmac
import hashlib
import base64

def send_sms_code(phone, code):
    """发送短信验证码（阿里云示例）"""
    params = {
        "PhoneNumbers": phone,
        "SignName": settings.SMS_CONFIG['SIGN_NAME'],
        "TemplateCode": settings.SMS_CONFIG['TEMPLATE_CODE'],
        "TemplateParam": '{"code":"%s"}' % code
    }
    
    # 构造阿里云API请求
    public_params = {
        "SignatureMethod": "HMAC-SHA1",
        "SignatureNonce": str(uuid.uuid4()),
        "AccessKeyId": settings.SMS_CONFIG['ACCESS_KEY_ID'],
        "SignatureVersion": "1.0",
        "Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "Format": "JSON",
        "Action": "SendSms",
        "Version": "2017-05-25",
        "RegionId": "cn-hangzhou"
    }
    
    # 合并参数
    all_params = {**public_params, **params}
    
    # 生成签名
    sorted_params = sorted(all_params.items())
    query_string = urlencode(sorted_params)
    string_to_sign = "GET&%2F&" + urlencode(query_string).replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
    key = settings.SMS_CONFIG['ACCESS_KEY_SECRET'] + "&"
    signature = base64.b64encode(hmac.new(key.encode(), string_to_sign.encode(), hashlib.sha1).digest()).decode()
    
    # 添加签名
    all_params["Signature"] = signature
    
    # 发送请求
    url = "http://%s/?%s" % (settings.SMS_CONFIG['ENDPOINT'], urlencode(all_params))
    response = requests.get(url)
    
    return response.json()

def user_login(request):
    if request.method == 'POST':
        form = PhoneNumberForm(request.POST)
        if form.is_valid():
            phone = form.cleaned_data['phone']
            # 生成验证码
            code = ''.join(random.choices('0123456789', k=6))
            
            # 存储验证码和手机号到数据库缓存，有效期5分钟
            cache_key = f'login_code_{phone}'
            cache.set(cache_key, {'code': code, 'phone': phone}, 300)
            
            # 发送短信
            result = send_sms_code(phone, code)
            if result.get('Code') == 'OK':
                # 将手机号存入session以便验证页面使用
                request.session['verification_phone'] = phone
                return redirect('verify_code')
            else:
                form.add_error('phone', '短信发送失败，请稍后重试')
    else:
        form = PhoneNumberForm()
    
    return render(request, 'sms_auth/login.html', {'form': form})

def verify_code(request):
    # 从session获取手机号
    phone = request.session.get('verification_phone')
    if not phone:
        return redirect('login')
    
    if request.method == 'POST':
        form = VerificationCodeForm(request.POST)
        if form.is_valid():
            code = form.cleaned_data['code']
            cache_key = f'login_code_{phone}'
            cached_data = cache.get(cache_key)
            
            if cached_data and cached_data['code'] == code:
                # 获取或创建用户
                user = User.get_or_create_user(phone)
                # 登录用户
                login(request, user)
                # 清除验证码和session中的手机号
                cache.delete(cache_key)
                del request.session['verification_phone']
                return redirect('home')
            
            form.add_error('code', '验证码错误或已过期')
    else:
        form = VerificationCodeForm()
    
    return render(request, 'sms_auth/verify.html', {'form': form, 'phone': phone})

def user_logout(request):
    logout(request)
    return redirect('login')

def home(request):
    if not request.user.is_authenticated:
        return redirect('login')
    return render(request, 'sms_auth/home.html', {'user': request.user})
